/**
 * 
 */
var queryStatisticCouponCodeSearch = function() {
	var queryStatisticCouponCodeFieldSet = new Ext.form.FieldSet({
				id : 'queryStatisticCouponCodeFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryStatisticCouponCode,
							scope : this
						}],
				buttons : [{
							text : '查询',
							handler : function() {
								queryStatisticCouponCode();
							}
						}, {
							text : '重置',
							handler : function() {
								queryStatisticCouponCodeForm.getForm().reset();
							}
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '优惠码名称',
											name : "couponCodeName"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '优惠码',
											name : "couponCode"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									xtype : "datefield",
									id : "statisticCouponCode_startDate",
									name : "statisticCouponCodeStartDate",
									fieldLabel : "创建开始日期",
									blankText : '请选择创建开始日期',
									editable : true,
									format : "Y-m-d",// 日期的格式
									width : 175,
									listeners : {
										'select' : function() {
											Ext
													.getCmp('statisticCouponCode_endDate')
													.setMinValue(this
															.getValue());
										}
									}
								}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									width : 175,
									id : "statisticCouponCode_endDate",
									xtype : "datefield",
									name : "statisticCouponCodeEndDate",
									fieldLabel : "创建结束日期",
									blankText : '请选择创建结束日期',
									editable : false,
									format : "Y-m-d",// 日期的格式
									listeners : {
										'select' : function() {
											Ext
													.getCmp('statisticCouponCode_startDate')
													.setMaxValue(this
															.getValue());
										}
									}
								}]
							}]
				}]
			});
	fieldSetListeners(['queryStatisticCouponCodeFieldSet',
					'queryStatisticCouponCodeForm', 'statisticCouponCodeGrid'],
			[0.18, 0.82]);
	var queryStatisticCouponCodeForm = new Ext.form.FormPanel({
				id : 'queryStatisticCouponCodeForm',
				anchor : '100% 18%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryStatisticCouponCodeFieldSet]
			});
	return queryStatisticCouponCodeForm;
};

/**
 * grids
 */
var statisticCouponCodeGrid = function() {
	// 定义表的每列（对应表头信息）
	var statisticCouponCodeCm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), {
				header : "订单编号",
				width : 80,
				sortable : true,
				dataIndex : 'id'
			}, {
				header : "订单编码",
				width : 80,
				sortable : false,
				dataIndex : 'orderCode',
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.id;
					if (value) {
						returnValue = '<a href ="#" onClick="couponLookOrderManagerDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				header : "用户编号",
				width : 80,
				sortable : false,
				dataIndex : 'userId'
			}, {
				header : "用户名",
				width : 80,
				sortable : false,
				dataIndex : 'userName'
			}, {
				header : "订单金额",
				width : 80,
				sortable : false,
				dataIndex : 'totalAmount',
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			}, {
				header : "优惠码",
				width : 80,
				sortable : true,
				dataIndex : 'couponCode'
			}, {
				header : "优惠金额",
				width : 80,
				sortable : false,
				dataIndex : 'couponFee',
				renderer : function(val) {
					return PmsUtil.Price(val);
				}
			}]);

	var statisticCouponCodeReader = new Ext.data.JsonReader({
				root : 'list',
				fields : [{
							name : 'id'
						}, {
							name : 'userId'
						}, {
							name : 'userName'
						}, {
							name : 'couponCode'
						}, {
							name : 'totalAmount'
						}, {
							name : 'couponType'
						}, {
							name : 'couponFee'
						}, {
							name : 'createdDate'
						}, {
							name : 'orderCode'
						}, {
							name : 'couponCodeName'
						}]
			});

	// 取数据store
	var statisticViewStore = new Ext.data.GroupingStore({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath
									+ "/statisticManager/selectSatasticCouponCode"
						}),
				groupField : 'couponCode',
				sortInfo : {
					field : 'couponCode',
					direction : 'ASC'
				},
				groupOnSort : true,
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams,
									Ext.getCmp('queryStatisticCouponCodeForm')
											.getForm().getValues());
						}
					}
				},
				reader : statisticCouponCodeReader
			});

	statisticViewStore.addListener('load', function() {
				if (statisticViewStore.getCount() > 0) {
					var grid = Ext.getCmp('statisticCouponCodeGrid')
					var totalAmountAll = 0.00;
					var couponFeeAll = 0.00;
					var gridrange = statisticViewStore.getRange();
					for (var i = 0; i < gridrange.length; i++) {
						var tmp = gridrange[i];
						var totalAmount = tmp.get("totalAmount");
						var couponFee = tmp.get("couponFee");
						if (totalAmount != null && totalAmount != 'undefined') {
							totalAmountAll += totalAmount
						}
						if (couponFee != null && couponFee != 'undefined') {
							couponFeeAll += couponFee;
						}
					}
					// 求使用次数总数、订单金额总数、优惠金额总数
					Ext.getCmp('useCouponCodeAllSum')
							.setValue('<div style="color:red;">'
									+ statisticViewStore.getCount() + '</div>');
					Ext.getCmp('totalAmountGridSum')
							.setValue('<div style="color:red;">'
									+ totalAmountAll + '</div>');
					Ext.getCmp('couponFeeGridSum')
							.setValue('<div style="color:red;">' + couponFeeAll
									+ '</div>');
				}
			});

	// 定义grid的toolbar
	var statisticCouponCodeTb = new Ext.Toolbar({
				id : "statisticCouponCodeTb",
				height : 25,
				items : []
			});
	statisticCouponCodeTb.add(new Ext.Toolbar.Spacer());
	statisticCouponCodeTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'statisticOrders_刷新',
				pressed : true,
				handler : function() {
					queryStatisticCouponCode();
				}
			}));
	statisticCouponCodeTb.add('->');
	statisticCouponCodeTb.add({
				xtype : 'displayfield',
				value : '使用次数总计：',
				style : 'margin-left : 30px;'
			}, {
				xtype : 'displayfield',
				id : 'useCouponCodeAllSum'
			}, {
				xtype : 'displayfield',
				value : '订单金额总计：',
				style : 'margin-left : 30px;'
			}, {
				xtype : 'displayfield',
				moneyFormat : '0,000.00',
				id : 'totalAmountGridSum'
			}, {
				xtype : 'displayfield',
				value : '优惠金额总计：',
				style : 'margin-left : 30px;'
			}, {
				xtype : 'displayfield',
				moneyFormat : '0,000.00',
				id : 'couponFeeGridSum'
			});

	var statsticCouponCodeView = new Ext.grid.GroupingView({
		forceFit : true,
		startCollapsed : true,
		hideGroupedColumn : true,
		collapsible : true,
		animCollapse : true,
		sortAscText : "升序",
		sortDescText : "降序",
		columnsText : "表格字段",
		groupByText : "使用当前字段进行分组",
		showGroupsText : "表格分组",
		groupTextTpl : [
				'{text}',
				'优惠码名称：{[values.rs[0].data.couponCodeName]}',
				'使用次数：{[getUseCouponCodeSum(values)]}',
				'订单金额总数：{[getTotalAmountSum(values)]}',
				'优惠总金额总数：{[getCouponFeeSum(values)]}',
				'<input  type="button" value="导出Excel"  onclick="exportStatisticsCouponCode(\'{[values.rs[0].data.couponCode]}\');"></input>']
	});

	var statisticCouponCodeGrid = new Ext.grid.GridPanel({
				id : 'statisticCouponCodeGrid',
				store : statisticViewStore,
				cm : statisticCouponCodeCm,
				view : statsticCouponCodeView,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				animCollapse : false,
				iconCls : 'icon-grid',
				tbar : statisticCouponCodeTb,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 82%',
				frame : true
			});
	return statisticCouponCodeGrid;
};

// 查询
function queryStatisticCouponCode() {
	var grid = Ext.getCmp("statisticCouponCodeGrid");
	var form = Ext.getCmp("queryStatisticCouponCodeForm");
	if (form.getForm().isValid()) {
		var gridStore = grid.getStore();
		gridStore.baseParams = Ext.apply(gridStore.baseParams, form.getForm()
						.getValues());
		gridStore.load();
	}
}

/**
 * 统计优惠券使用次数
 */
function getUseCouponCodeSum(couponCodeRecod) {
	return couponCodeRecod.rs.length;
}

/**
 * 计算订单总金额总数
 * 
 * @param {}
 *            groupRecod
 * @return {}
 */
function getTotalAmountSum(groupRecod) {
	var totalAmountSum = 0.00;
	for (var i = 0; i < groupRecod.rs.length; i++) {
		var recode = groupRecod.rs[i].data;
		totalAmountSum += recode.totalAmount;
	}
	return PmsUtil.Price(totalAmountSum);
};

/**
 * 计算优惠券总金额
 * 
 * @param {}
 *            groupRecod
 */
function getCouponFeeSum(groupRecod) {
	var couponFee = 0;
	for (var i = 0; i < groupRecod.rs.length; i++) {
		var recode = groupRecod.rs[i].data;
		couponFee += recode.couponFee;
	}
	return couponFee;
}

/**
 * 根据优惠码导出excel
 * 
 * @param {}
 *            couponCode
 */
function exportStatisticsCouponCode(couponCode) {
	var statisticCouponCodeStartDate = PmsUtil.formatDate(Ext
			.getCmp('statisticCouponCode_startDate').getValue());
	var statisticCouponCodeEndDate = PmsUtil.formatDate(Ext
			.getCmp('statisticCouponCode_endDate').getValue());
	document.location.href = (__ctxPath
			+ "/statisticManager/exportStatisticsCouponCode?couponCode="
			+ couponCode + "&statisticCouponCodeStartDate="
			+ statisticCouponCodeStartDate + "&statisticCouponCodeEndDate=" + statisticCouponCodeEndDate);
}
/**
 * 查看订单详情
 * @param {} id
 */
function couponLookOrderManagerDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.ORDER_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookOrderDetailFields',
						'lookOrderDetailForm', 'lookOrderDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/order/orderDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookOrderDetailSearch(id), orderDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

Ext.getCmp("centerTabPanel").getActiveTab().add(
		queryStatisticCouponCodeSearch(), statisticCouponCodeGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
